package com.rxyb.security.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rxyb.security.db.bean.SysMenu;
import com.rxyb.security.db.dao.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @author YJH
 * @version 1.0
 * @description 路由动态获取角色
 * @date 2020/5/16  16:47
 */
@Service
public class UrlRolesFilterHandler implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysMenuMapper sysMenuMapper;


    /**
     * 首先增加一个处理类，在收到访问的时候，动态获取当前url的角色：
     *
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysMenu::getUrl, requestUrl);
        List<SysMenu> sysMenus = sysMenuMapper.selectList(queryWrapper);
        String[] names = new String[sysMenus.size()];
        for (int i = 0; i < sysMenus.size(); i++) {
            names[i] = sysMenus.get(i).getUrl();
        }
        return SecurityConfig.createList(names);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
